package com.olah.common.utils;

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

public class RsaUtils {

    private static final int DEFAULT_SIZE = 1024;
    private static final String KEY_ALGORITHM = "RSA";

    public static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKH6+CpeJM+eLR4EwVn1ieuMFyqa8YkpVLo+Ug8sD+HNK1vUH6coRho+LWUMIBltLV6mz+5tseRLIGeJJE0SH+FtkajOOVngThlkXCFLbDOSORtY9EJQnJjHS/y6QLjOs7Vpv6cYz+3cuDE3BBAUrIt7F24VqCGu6+PGafCrA9W3AgMBAAECgYBJN+ClhhitoJpUT2H2//5v8ssl/xPfJEegSDtfkFM9hjhrMd989794bVKnsmtwEuHHPzAOXpdi0nK7WkqGbALsbvfMSPrYQE3eK47ouQSgXtyU646A3h/fUgyC3/yik7QYSlg8gbZt4e2kclWhYib73kFghBLC+dY1Fl6cALHHQQJBAPxmlQj2eU99Fy86DLKVg8QdyCoPN5JoGjktEn8PBqZfULN8wbDVo2FPmIPwr9ndNM6kl33r9HZVkpHL8HL5KpMCQQCkSkwbek+0Xfv5JpszKqvnTCtcfjPoBjJ9+sjwdycPCdVX49kVaEkG9Tox2RCFZsHalY2/mLg1QjEE4iVHwQrNAkEA1Zdp35/UoPPWvtx9ClOEol4hmZYvDPKT3nbKBEQO+JQIkxusPZ1NGXhmNKFl7xRHL+gRWzpmMg3QbxkKbgF1iQJAFIiQsJJ96b4hYwd3OFLp/1Oey8WeOS6lGufAO4W45QFGn+CDXlCVaAA4UMifbvzj16z/dWXiCA4I0GJvZGN1NQJBAN1QUj2me+Ft6yyKhAJgDyTUaHYgwnnQwIe8Fb1WvsklkGQWUmZqQpaWoHjSMwqwb3pR/V5n+nEXLL36dMVkhhk=";

    public static Map<String, String> getKeys(int size) {
        Map<String, String> result = new HashMap<>(2);
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            kpg.initialize(size, new SecureRandom());
            KeyPair kp = kpg.generateKeyPair();
            result.put("public", new String(Base64.encodeBase64(kp.getPublic().getEncoded())));
            result.put("private", new String(Base64.encodeBase64(kp.getPrivate().getEncoded())));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String dencrypt(String source) {
        if (source == null)
            return null;
        byte[] inputByte;
        String outStr = "";
        try {
            inputByte = Base64.decodeBase64(source.getBytes(UTF_8));
            byte[] decoded = Base64.decodeBase64(PRIVATE_KEY);
            RSAPrivateKey RSAPrivateKey = (RSAPrivateKey) KeyFactory.getInstance(KEY_ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, RSAPrivateKey);
            outStr = new String(cipher.doFinal(inputByte));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outStr;
    }

}